package com.yange.accountbook.ui

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.OnSelectListener
import com.yange.accountbook.databinding.AddItemFragmentBinding
import com.yange.accountbook.entity.AccountEntity
import com.yange.accountbook.entity.BooksEntity
import com.yange.accountbook.entity.IconEntity
import com.yange.accountbook.entity.ModuleEntity
import com.yange.accountbook.events.AccountDetailChangeEvent
import com.yange.accountbook.net.Api
import com.yange.accountbook.net.BaseResponse
import com.yange.accountbook.net.api.RetrofitClient
import com.yange.accountbook.net.observable.RecObserver
import com.yange.accountbook.popup.AccountListBottomPop
import com.yange.accountbook.popup.BookListBottomPop
import com.yange.accountbook.ui.adapter.IconAdapter
import com.yange.accountbook.utils.showToast
import org.greenrobot.eventbus.EventBus
import java.util.stream.Collectors

class AddItemInFragment : BaseFragment<AddItemFragmentBinding>() {


    val TYPE_OUT = "OUT" //支出
    val TYPE_IN = "IN" //收入
    val TYPE_SPLIT = "SPLIT" //分账
    val TYPE_TRANSFER = "TRANSFER" //转账
    var orderType = ""
    lateinit var iconAdapter: IconAdapter
    lateinit var accountModules: List<ModuleEntity>

    var bookId = 0
    var accountId = 0
    var splitId = 0
    var icon = ""
    var inAccountId = 0
    var inBookId = 0

    override fun initView() {
        iconAdapter = IconAdapter()
        binding.dataList.layoutManager = GridLayoutManager(activity, 4)
        binding.dataList.adapter = iconAdapter
        orderType = arguments?.getString("type") ?: ""
        if (TYPE_SPLIT == orderType) {
            accountModules = arrayListOf()
            binding.layoutModule.visibility = View.VISIBLE
            binding.lineModule.visibility = View.VISIBLE
            binding.layoutRemark.visibility = View.GONE
            binding.lineRemark.visibility = View.GONE
        }
        if (TYPE_TRANSFER == orderType){
            binding.layoutRemark.visibility = View.GONE
            binding.lineRemark.visibility = View.GONE

            binding.layoutInBook.visibility = View.VISIBLE
            binding.lineInBook.visibility = View.VISIBLE

            binding.lineInAccount.visibility = View.VISIBLE
            binding.layoutInAccount.visibility = View.VISIBLE
        }
        initAccount()
        initListener()
    }

    fun initAccount(){
        accountId = arguments?.getInt("accountId") ?: 0
        bookId = arguments?.getInt("bookId") ?: 0
        if (accountId == 0){
            return
        }
        RetrofitClient.getInstance().invokeGetBookInfo(context, bookId)
            .subscribe(object : RecObserver<BaseResponse<BooksEntity>>(context, true, false) {
                override fun onSuccess(t: BaseResponse<BooksEntity>?) {
                    binding.tvBook.text = t!!.data.name
                }
                override fun onFail(msg: String, code: Int) {
                    showToast(msg)
                }
            })

        RetrofitClient.getInstance().invokeGetAccountInfo(context, accountId)
            .subscribe(object : RecObserver<BaseResponse<BooksEntity>>(context, true, false) {
                override fun onSuccess(t: BaseResponse<BooksEntity>?) {
                    binding.tvAccount.text = t!!.data.name
                }
                override fun onFail(msg: String, code: Int) {
                    showToast(msg)
                }
            })
    }


    fun initListener() {

        //账本点击
        binding.tvBook.setOnClickListener {
            XPopup.Builder(activity)
                .hasShadowBg(true)
                .asCustom(activity?.let { it1 ->
                    BookListBottomPop(it1, object : BookListBottomPop.OnItemClickListener {
                        override fun itemClick(item: BooksEntity) {
                            bookId = item.id
                            binding.tvBook.text = item.name
                            buildAccount()
                        }
                    })
                })
                .show()
        }

        //账户点击
        binding.tvAccount.setOnClickListener {
            if (bookId == 0) {
                showToast("请先选择账本")
                return@setOnClickListener
            }
            buildAccount()
        }

        //保存
        binding.btnCommit.setOnClickListener {
            if (bookId == 0) {
                showToast("请先选择账本")
                return@setOnClickListener
            }
            if (accountId == 0) {
                showToast("请先选择账户")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(binding.editBookMoney.text)) {
                showToast("请输入金额")
                return@setOnClickListener
            }
            if (TYPE_SPLIT == orderType) {
                if (splitId == 0) {
                    showToast("请先选择分账模式")
                    return@setOnClickListener
                }
            } else if(TYPE_TRANSFER == orderType){
                if (inAccountId == 0) {
                    showToast("请先收款账户")
                    return@setOnClickListener
                }
            } else {
                if (TextUtils.isEmpty(binding.editRemark.text)) {
                    showToast("请输入备注")
                    return@setOnClickListener
                }
            }
            commit()
        }

        if (TYPE_IN == orderType || TYPE_OUT == orderType) {
            getIconList()
            //图标点击
            iconAdapter.setOnItemClickListener { adapter, view, position ->

                var item = adapter.getItem(position) as IconEntity
                iconAdapter.setChecked(position)
                binding.editRemark.setText(item.name)
                icon = item.icon
                if (binding.layoutInput.visibility == View.GONE) {
                    binding.layoutInput.visibility = View.VISIBLE
                }
            }
        } else if (TYPE_TRANSFER == orderType){
            //账本点击
            binding.tvInBook.setOnClickListener {
                XPopup.Builder(activity)
                    .hasShadowBg(true)
                    .asCustom(activity?.let { it1 ->
                        BookListBottomPop(it1, object : BookListBottomPop.OnItemClickListener {
                            override fun itemClick(item: BooksEntity) {
                                inBookId = item.id
                                binding.tvInBook.text = item.name
                                buildInAccount()
                            }
                        })
                    })
                    .show()
            }

            //账户点击
            binding.tvInAccount.setOnClickListener {
                if (bookId == 0) {
                    showToast("请先收款账本")
                    return@setOnClickListener
                }
                buildInAccount()
            }
        } else {
            //账户点击
            binding.tvModule.setOnClickListener {
                getAccountModuleList()
            }
        }
    }

    /**
     * 获取账本详情
     */
    fun getAccountModuleList() {
        if (accountModules.isNotEmpty()) {
            buildAccountModule()
            return
        }
        RetrofitClient.getInstance().invokePostBody(context, Api.SPLIT_ACCOUNT_LIST, mapOf())
            .subscribe(object :
                RecObserver<BaseResponse<List<ModuleEntity>>>(context, true, false) {
                override fun onSuccess(t: BaseResponse<List<ModuleEntity>>?) {
                    accountModules = t!!.data
                    buildAccountModule()
                }

                override fun onFail(msg: String, code: Int) {
                }
            })
    }

    fun buildAccountModule() {
        if (accountModules.isNullOrEmpty()) {
            return
        }
        val bookNames = accountModules.stream().map { it.name }.collect(Collectors.toList());
        XPopup.Builder(context)
            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
            .asCenterList("请选择账本", bookNames.toTypedArray(),
                null, 0,
                object : OnSelectListener {
                    override fun onSelect(position: Int, text: String) {
                        splitId = accountModules[position].id
                        binding.tvModule.text = text
                    }
                })
            .show()
    }
    fun buildInAccount() {
        XPopup.Builder(activity)
            .asCustom(activity?.let { it1 ->
                AccountListBottomPop(
                    it1,
                    inBookId,
                    object : AccountListBottomPop.OnItemClickListener {
                        override fun itemClick(item: AccountEntity) {
                            inAccountId = item.id
                            binding.tvInAccount.text = item.name
                        }
                    })
            })
            .show()
    }

    fun buildAccount() {
        XPopup.Builder(activity)
            .asCustom(activity?.let { it1 ->
                AccountListBottomPop(
                    it1,
                    bookId,
                    object : AccountListBottomPop.OnItemClickListener {
                        override fun itemClick(item: AccountEntity) {
                            accountId = item.id
                            binding.tvAccount.text = item.name
                        }
                    })
            })
            .show()
    }

    fun commit() {
        RetrofitClient.getInstance().invokePostBody(
            context, Api.ACCOUNT_RECORD_SAVE, mapOf(
                "accountId" to accountId,
                "money" to binding.editBookMoney.text.toString().toDouble(),
                "name" to binding.editRemark.text.toString(),
                "type" to orderType,
                "splitId" to splitId,
                "icon" to icon,
                "fromId" to inAccountId
            )
        ).subscribe(object : RecObserver<BaseResponse<Any>>(context, true, false) {
            override fun onSuccess(t: BaseResponse<Any>?) {
                showToast("添加成功")
                activity?.finish()
                EventBus.getDefault().post(AccountDetailChangeEvent(bookId, accountId))
            }

            override fun onFail(msg: String, code: Int) {
                showToast(msg)
            }
        })
    }

    override fun initData() {}


    private fun getIconList() {
        RetrofitClient.getInstance().invokeGetIconList(activity, arguments?.getString("type"))
            .subscribe(object :
                RecObserver<BaseResponse<List<IconEntity>>>(activity, true, false) {
                override fun onSuccess(t: BaseResponse<List<IconEntity>>?) {
                    if (!t?.data.isNullOrEmpty()) {
                        iconAdapter.setNewInstance(t?.data as MutableList<IconEntity>?)
                    }
                }

                override fun onFail(msg: String, code: Int) {

                }
            })
    }


    companion object {

        fun newInstance(type: String): AddItemInFragment {
            var fragment = AddItemInFragment()
            var bundle = Bundle()
            bundle.putString("type", type)
            fragment.arguments = bundle
            return fragment
        }
        fun newInstance(type: String, accountId: Int, bookId: Int): AddItemInFragment {
            var fragment = AddItemInFragment()
            var bundle = Bundle()
            bundle.putString("type", type)
            bundle.putInt("accountId", accountId)
            bundle.putInt("bookId", bookId)
            fragment.arguments = bundle
            return fragment
        }

    }


}